package com.calvin.study.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.calvin.study.base.ResponseModel;
import com.calvin.study.exception.CustomException;
import com.calvin.study.exception.CustomExceptionType;
import com.calvin.study.service.sys.security.JwtAuthService;

@RestController
public class JwtAuthController {

	@Autowired
	private JwtAuthService jwtAuthService;

	// 请求认证入口
	@RequestMapping(value = "/authentication")
	public ResponseModel login(@RequestBody Map<String, String> map) {
		String username = map.get("username");
		String password = map.get("password");

		if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
			return ResponseModel.error(new CustomException(CustomExceptionType.USER_INPUT_ERROR, "用户名或者密码不能为空"));
		}
		try {
			return ResponseModel.success(jwtAuthService.login(username, password));
		} catch (CustomException e) {
			return ResponseModel.error(e);
		}
	}

	@RequestMapping(value = "/refreshtoken")
	public ResponseModel refresh(@RequestHeader("${jwt.header}") String token) {
		return ResponseModel.success(jwtAuthService.refreshToken(token));
	}

}
